import uiautomation as auto

from comtypes.gen.UIAutomationClient import IUIAutomation

class UiautoBiz(object):
  def __init__(this):
    auto.SetGlobalSearchTimeout(2)  # 设置全局搜索超时时间为2秒
    auto.CalendarControl()
    this.hehe = IUIAutomation()
  def getEdgeWindow(this):
    window = auto.WindowControl(searchDepth=1,ClassName="Chrome_WidgetWin_1")
    return window
  def getEdgeBody(this):
    window = auto.WindowControl(searchDepth=1,ClassName="Chrome_WidgetWin_1")
    return this.getBodyNode(window)
  # 激活窗口
  def setActive(this,window):
    window.SetActive()
  # 窗口置顶
  def setTopMost(this,window):
    window.SetTopMost() 
  def getBodyNode(this,window):
      child = window.Control(ClassName="BrowserView")
      child = child.Control(ClassName="Chrome_RenderWidgetHostHWND")
      child = child.Control(className="GroupControl")
      # this.printAllNode(child)
      return child
  # 通过className,读取text内容
  def readTxtByClassName(this,node,className):
    try:
      find = node.Control(ClassName = className)
      return find.Name
    except Exception as ex:
      print(ex)
      return ''
  def getChildIndex(this,node,index):
    childs = node.GetChildren()
    return childs[index]
  #打印子节点
  def printChilds(this,node):
    childs = node.GetChildren()
    i = 0
    print('node.par','child.size='+str(len(childs)),node)
    for item in childs:
      print(i,item)
      i+=1
  #打印所有节点信息,返回strLs
  def printAllNode(this,node):
    childs = node.GetChildren()
    strLs = []
    this.printAllNodeCecur(childs,0,'0',strLs)
    return strLs
  def printAllNodeCecur(this,childs,lv,parStr,strLs):
    blankStr= ''
    for i in range(0,lv):
      blankStr+='  '
    index = 0
    for item in childs:
      one = blankStr+parStr+'-'+str(index)+': ' + str(item)
      print(one)
      strLs.append(one)
      ccc = item.GetChildren()
      if len(ccc) > 0:
        this.printAllNodeCecur(ccc,lv+1,parStr+'-'+str(index),strLs)
      index += 1
  def strLsToStr(this,strLs):
    sss = ''
    i = 0
    for item in strLs:
      if i !=0 :
        sss += '\n'
      sss += item
      i+=1
    return sss


# c = auto.ControlFromCursor().GetTopLevelControl() // 获取当前鼠标位置对应的窗口：
  # c = auto.GetForegroundControl().GetTopLevelControl() // 获取当前激活窗口对应的对象：
  # auto.Click(x, y) 鼠标点击指定坐标：
  # auto.RightClick(x, y) 右键单击：
  # auto.DragDrop(x1, y1, x2, y2, moveSpeed=1) 鼠标拖拽(鼠标从(x1,y1)位置按下鼠标拖动到(x2,y2)位置)：

  # control.GetFirstChildControl() 获取首个子控件：
  # control.GetLastChildControl() 获取最后一个子控件
  # control.GetChildren() 获取所有的子控件：
  # control.GetParentControl()


  # win = auto.ControlFromCursor().GetTopLevelControl() 假设获取到一个窗口对象：
  # win.NativeWindowHandle  获取本地窗口句柄：
  # win2 = auto.ControlFromHandle(win.NativeWindowHandle) // 根据本地窗口句柄获取窗口控件对象：

  # auto.SetClipboardText('Hello World')
  # with auto.Bitmap.FromFile(path)as bmp:
    # auto.SetClipboardBitmap(bmp)